/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-11-06     Ghazigq     the first version
 */

#include <board.h>
#define BSP_USING_ADC

#if defined(BSP_USING_ADC)
#include "drv_adc.h"
#include <rtdevice.h>

//#define DRV_DEBUG
#define LOG_TAG             "drv.adc"
#include <drv_log.h>

static struct rt_adc_device nrf_adc_device;

static const nrfx_saadc_config_t default_config = NRFX_SAADC_DEFAULT_CONFIG;

static rt_err_t nrf_adc_enabled(struct rt_adc_device *device, rt_uint32_t channel, rt_bool_t enabled)
{
    RT_ASSERT(channel < 8);

    if(enabled)
    {
        nrf_saadc_channel_config_t channel_config = NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE(channel + 1);

        if(nrfx_saadc_channel_init(channel, &channel_config) != NRFX_SUCCESS)
            LOG_E("adc channel(%d) enable failed!", channel);
    }
    else
    {
        if(nrfx_saadc_channel_uninit(channel) != NRFX_SUCCESS)
            LOG_E("adc channel(%d) disable failed!", channel);
    }
    return RT_EOK;
}


static rt_err_t nrf_get_adc_value(struct rt_adc_device *device, rt_uint32_t channel, rt_uint32_t *value)
{
    nrf_saadc_value_t adc_value = 0;

    if(nrfx_saadc_sample_convert(channel, &adc_value) != NRFX_SUCCESS)
    {
        LOG_E("adc channel(%d) read failed!", channel);
        *value = 0;
        return -RT_ERROR;
    }
    if(default_config.resolution == 0)
        *value = adc_value * 3600 / 256;//8位ADC  配置参考电压为0.6/Gain（1/6）
    else if(default_config.resolution == 1)
        *value = adc_value * 3600 / 1024;//10位ADC  配置参考电压为0.6/Gain（1/6）
    else if(default_config.resolution == 2)
        *value = adc_value * 3600 / 4096;//12位ADC  配置参考电压为0.6/Gain（1/6）
    else if(default_config.resolution == 3)
        *value = adc_value * 3600 / 16384;//14位ADC  配置参考电压为0.6/Gain（1/6）

    return RT_EOK;
}

static const struct rt_adc_ops nrf_adc_ops =
{
  .enabled = nrf_adc_enabled,
  .convert = nrf_get_adc_value,
};

static int nrf_adc_init(void)
{

    if(nrfx_saadc_init(&default_config, RT_NULL) != NRFX_SUCCESS)
    {
        LOG_E("adc init failed!");
        return -RT_ERROR;
    }

    RT_ASSERT(rt_hw_adc_register(&nrf_adc_device, "adc", &nrf_adc_ops, RT_NULL) == RT_EOK);
    return RT_EOK;
}
INIT_BOARD_EXPORT(nrf_adc_init);

void SAADC_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();



    /* leave interrupt */
    rt_interrupt_leave();
}

#endif /* BSP_USING_ADC1 */

